package com.zc.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.zc.common.BaseResult;
import com.zc.model.Payment;
import com.zc.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @description:
 * @author: cong
 * @create: 2024/9/29
 */
@RestController
@Slf4j
public class PaymentController {
    public static final Logger logger = LoggerFactory.getLogger(PaymentController.class);
    @Resource
    private PaymentService paymentService;

    @Resource
    private DiscoveryClient discoveryClient;

    @PostMapping("/create")
    public BaseResult create(@RequestBody Payment payment) {
        return paymentService.save(payment) ? BaseResult.success("插入数据成功", payment)
                : BaseResult.fail("插入数据失败");
    }

    @GetMapping(value = "/query/{id}")
    public BaseResult getPaymentById(@PathVariable("id") Long id) {
        Payment payment = paymentService.getById(id);
        if (payment != null) {
            return BaseResult.success("查询成功", payment);
        }
        return BaseResult.fail("查询失败");
    }

    @GetMapping("/discovery")
    public Object discovery() {
        discoveryClient.getServices().forEach(service -> {logger.info("service: " + service);});
        return discoveryClient;
    }

    @GetMapping("/hystrix/ok")
    public String visitOK() {
        return paymentService.paymentInfoOk();
    }

    @GetMapping("/hystrix/timeout")
    // 服务端服务降级
//    @HystrixCommand(fallbackMethod = "fallback", commandProperties = {
//            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
//    })
    public String visitTimeout() {
        return paymentService.paymentTimeOut();
    }


    public String fallback() {
        return "好烦，接近理想好难！";
    }
}
